﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace AggregateRoot.Console
{
    class AggregateRootWithChildOperation
    {
        #region Update Order -- CRUD Child Tables (with composite key)

        //CRUD -- Child Data

        public static void Update_Order_Add_Child_Order_Details_Data()
        {
            DataContext db = new DataContext();
            OrderRepository orderRep = new OrderRepository(db);
            Order order = orderRep.GetByOrderId(11078);

            Order_Detail order_Details = new Order_Detail();
            order_Details.Quantity = 10;
            order_Details.Product = new ProductRepository(db).GetByProductId(1);

            //the statement below performs two operations
            //1. a foreign key assignment in the order details table
            //2. a database row insert of order details table
            order.Order_Details.Add(order_Details);
            
            orderRep.Save();
        }

        public static void Update_Order_Update_Child_Order_Details_Data()
        {
            DataContext db = new DataContext();
            OrderRepository orderRep = new OrderRepository(db);
            Order order = orderRep.GetByOrderId(11078);

            //Order_Detail order_Details = order.Order_Details.AsQueryable().SingleOrDefault(od => od.ProductID == 1);
            Order_Detail order_Details = order.Order_Details.Single(od => od.ProductID == 1);
            //order.Order_Details.Add(order_Details); //also works without any extra impact
            
            //the statement below performs an data field update in the order details row
            order_Details.Quantity = 40;
            
            orderRep.Save();
        }

        public static void Update_Order_Delete_Child_Order_Details_Data()
        {
            DataContext db = new DataContext();
            OrderRepository orderRep = new OrderRepository(db);
            Order order = orderRep.GetByOrderId(11078);

            //Order_Detail order_Details = order.Order_Details.AsQueryable().SingleOrDefault(od => od.ProductID == 1);
            Order_Detail order_Details = order.Order_Details.Single(od => od.ProductID == 1);
            
            //the statement below performs two operations
            //1. removes the foreign key entry from the order details row
            //2. removes the order details row
            order.Order_Details.Remove(order_Details);//deletes the physical row of child!
            

            orderRep.Save();
        }

        #endregion
    }
}
